package com.shp.utils;

import com.shp.pojo.Admin;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Description:
 * 管理员登陆拦截器
 *
 * @author zwl
 * @version 1.0
 * @date 2020/3/15 20:44
 */
public class AdminPowerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求路径
        String uri = request.getRequestURI();
        System.out.println("+++++++++++++++++++++++++++：" + uri);
        // 获取session
        HttpSession session = request.getSession();

        // 获取管理员
        Admin admin = (Admin) session.getAttribute("admin");
        // 如果已经登陆
        if (admin != null) {
            // 放行
            return true;
        }
        // 获取虚拟路径
        String basePath = request.getServletContext().getAttribute("basePath").toString();
        System.out.println("++++++++++++++++++++++++++：" + basePath);
        // 重定向到登陆页面
        response.sendRedirect(basePath + "/admin/login");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
